<?php
namespace Model;
use GFPHP\Db;
use GFPHP\Loader,GFPHP\Config;
if (!defined('__ROOT__')) exit('Sorry,Please from entry!');

/**
 * Model基类
 * 所有模型必须继承此类
 * 你也可以不使用模型，仅使用此Model
 * 创建时间：2014-08-10 07:52 PGF
 * 修改时间：2015-06-18 10:31 PGF            function __Clone(){}
 * @package Model
 * @method Model Select(string $field='')
 * @method Model Between(string $field,string $Between)
 * @method Model BotBetween(string $field,string $Between)
 * @method Model In(string $field,string $in)
 * @method Model Where(string $field,string $compar = '',string $val = '')
 * @method Model OrderBy(string $orderby='')
 * @method Model Limit(string $limit)
 * @method Model orwhere(string $field,string $val)
 * @method Model Update(array $update)
 * @method Model exec(string $sql='')
 * @method array query(string $sql='')
 * @method int|bool insert(array $insert)
 * @method Model leftJoin($table, $on1, $on2)
 * @method Model rightJoin($table, $on1, $on2)
 * @method Model Join($table, $on1, $on2)
 * @method Model fullJoinjoin($table='', $on1='', $on2='')
 * @method Model innerJoin($table='', $on1='', $on2='')
 * @method Model union(bool $all='')
 * @method Model delete($table='', $where='', $orderby='', $limit='')
 * @method Model group($group='')
 * @method Model compile()
 */
class Model
{
    /**
     * @var Db
     */
    public $db;

    protected $model;

    //-----初始化模型
    /**
     * Model constructor.
     * @param bool $model
     */
    public function __construct($model=false)
    {
        if($model)
            $this->model = $model;
        $this->database();
    }

    /**
     * @return String
     */
    final public function version()
    {
        $version = $this->getOne('VERSION()');
        return isset($version['VERSION()'])?$version['VERSION()']:null;
    }
    /**
     * database 加载数据库
     * @return null
     */
    private function database()
    {
        $db = Loader::database();
        if (!$db) {
            exit('<h1>Database Config Error!!!</h1>');
        }
        $class = substr(get_class($this),6);
        $num = strpos($class, 'Model');
        if ($num != 0) {
            $db->table = Config::database('table_pre') . substr($class, 0, $num);
        } else {
            $db->table = Config::database('table_pre') . substr($this->model, 0, strpos($this->model, 'Model'));
        }
        $db->_reset();
        $this->db = $db;
    }

    //设置模型操作的表
    /**
     * @param string $table
     * @return $this
     */
    public function table($table = '')
    {
        $this->db->table = Config::database('table_pre') . Config::database($table);
        return $this;
    }

    /**
     * 获取分页内容
     * @param int $number
     * @param int $page
     * @return array|mixed
     */
    public function paginate($number=10,$page=1){
        $page = $page>0?$page:1;
        $min = (intval($page)-1)*$number;
        return $this->db->limit($min, intval($number))->query();
    }

    /**
     * @param $field
     * @return int    获取到的数量
     */
    public function count($field='*')
    {
        $count = $this->getOne('count('.$field.')');
        return isset($count['count('.$field.')'])?$count['count('.$field.')']:0;
    }

    /**
     * 获取一条数据
     * @param array|string $field
     * @return bool or array
     */
    public function getOne($field='*'){
        $this->db->select($field);
        $this->db->limit(0,1);
        $fetch=$this->db->query();
        if(empty($fetch))
            return false;
        else
            return $fetch[0];
    }

    //=====不存在的方法将执行DB类中的方法=====//
    /**
     * @param $func Db
     * @param $val Db
     * @return Model|Db
     */
    public function __call($func, $val)
    {
        /** @var array $val */
        switch (count($val)) {
            case 0:
                return $this->_autoreturn($this->db->$func());
                break;
            case 1:
                return $this->_autoreturn($this->db->$func($val[0]));
                break;
            case 2:
                return $this->_autoreturn($this->db->$func($val[0], $val[1]));
                break;
            case 3:
                return $this->_autoreturn($this->db->$func($val[0], $val[1], $val[2]));
                break;
            case 4:
                return $this->_autoreturn($this->db->$func($val[0], $val[1], $val[2], $val[3]));
                break;
            case 5:
                return $this->_autoreturn($this->db->$func($val[0], $val[1], $val[2], $val[3], $val[4]));
                break;
            default:
                exit('不好意思了，只支持最多五个参数了，可以使用模型->db->方法执行操作！');
                break;
        }
    }
    //------自动更改调用方法

    /**
     * @param $res
     * @return Model
     */
    private function _autoreturn($res)
    {
        if (is_object($res)) {
            $this->db = $res;
            return $this;
        } else
            return $res;
    }

    /**
     * 防止clone Model出现DB对象还原的情况
     * @return mixed
     */
    public function __clone(){
        return $this->db = clone $this->db;
    }

    /**
     * 转义函数
     * 参数可以为多参数或数组，返回数组
     */
    public static function addslashes(&$var)
    {
        if (func_num_args() > 1) {
            $args = func_get_args();
            for ($i = 0; $i < func_num_args(); $i++) {
                $args[$i] = self::addslashes($args[$i]);
            }
            return $args;
        }
        if (!@get_magic_quotes_gpc()) {
            if (is_array($var)) {
                foreach ($var as $k => &$v) {
                    self::addslashes($v);
                }
            } else {
                $var = addslashes($var);
            }
            return $var;
        }
        return $var;
    }

    public static function stripslashes(&$var)
    {
        if (func_num_args() > 1) {
            $args = func_get_args();
            for ($i = 0; $i < func_num_args(); $i++) {
                $args[$i] = self::stripslashes($args[$i]);
            }
            return $args;
        }
        if (!@get_magic_quotes_gpc()) {
            if (is_array($var)) {
                foreach ($var as $k => &$v) {
                    self::stripslashes($v);
                }
            } else {
                $var = stripslashes($var);
            }
            return $var;
        }
        return $var;
    }
}

//====================    END Model.class.php      ========================//